<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    custom-class="mydialog"
    width="800px"
    :title="dialogTitle"
    :before-close="close"
  >
    <el-form
      ref="formRef"
      v-loading="dataLoading"
      element-loading-text="数据加载中..."
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-form-item
        label="配送商名称"
        prop="distributeName"
      >
        <div class="label">{{ formData.distributeName }}</div>

      </el-form-item>
      <el-form-item
        v-if="dialogType==='edit'"
        label="配送服务编号"
        prop="distributeServeNo"
      >
        <div class="label">{{ formData.distributeServeNo }}</div>

      </el-form-item>
      <el-form-item
        label="配送产品"
        prop="productId"
      >
        <template v-if="dialogType==='create'">
          <el-row>
            <div style="width: 100%;">
              <el-select
                v-model="formData.productId"
                style="width: 100%;"
                filterable
                clearable
                remote
                reserve-keyword
                :remote-method="proRemoteMethod"
                :loading="proLoading"
                value-key="id"
                placeholder="请选择产品"
                @change="selectChange"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="getProductName(item)"
                  :value="item.id"
                >
                  <div class="pro-item">
                    <span>{{ getProductName(item) }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>
          </el-row>
        </template>
        <template v-else>
          <div>
            {{ getProductName(formData) }}
          </div>
        </template>
      </el-form-item>
      <el-form-item
        v-if="dialogType==='changeInfo'"
        label="配送费"
      >
        <div>
          <div v-if="formData.computeMode==='固定价格'">
            <span>{{ formData.distributePrice }}元</span>
            <span>/{{ getLabel('sell_unit',formData.sellUnit) }}</span>
          </div>
          <div v-if="formData.computeMode==='终端价百分比'">
            <span>{{ formData.distributePercent }}%</span>
            <span>终端价</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        v-else
        label="配送费"
        :prop="formData.computeMode==='固定价格'?'distributePrice':'distributePercent'"
      >
        <el-row style="margin-bottom: 20px">
          <el-col :span="6">
            <el-radio
              v-model="formData.computeMode"
              label="固定价格"
              value="固定价格"
              @change="radioChange"
            >固定价格</el-radio>
          </el-col>
          <el-col :span="6">
            <el-radio
              v-model="formData.computeMode"
              label="终端价百分比"
              value="终端价百分比"
              @change="radioChange"
            >按终端价百分比</el-radio>
          </el-col>
        </el-row>
        <el-row>
          <el-col
            v-if="formData.computeMode==='固定价格'"
            :span="24"
          >
            <el-input
              v-model="formData.distributePrice"
              placeholder="请输入配送费"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
              @blur="()=>formData.distributePrice = Number(formData.distributePrice)"
            >
              <template #append><span>元</span><span v-if="formData.sellUnitLabel"> / {{ formData.sellUnitLabel }}</span></template>
            </el-input>
          </el-col>
          <el-col
            v-if="formData.computeMode==='终端价百分比'"
            :span="24"
          >
            <el-input
              v-model="formData.distributePercent"
              placeholder="请输入配送费"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
              @blur="()=>formData.distributePercent = Number(formData.distributePercent)"
            >
              <template #append><span>%</span></template>
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="配送地区"
        prop="area"
      >
        <el-cascader
          ref="cascader"
          v-model="formData.area"
          :popper-append-to-body="false"
          style="width: 100%;"
          :options="citys"
          placeholder="请选择配送地区"
          :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
          collapse-tags
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item
        label="关联合同"
        prop="contractId"
      >
        <el-select
          v-model="formData.contractId"
          style="width: 100%"
          filterable
          placeholder="请选择合同"
        >
          <el-option
            v-for="item in contractOptions"
            :key="item.id"
            :label="item.contractName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="服务结束日期"
        prop="expireTime"
      >
        <date-picker
          v-model:date="formData.expireTime"
          :disabled-date="disabledDate"
          style="width: 100%"
          type="date"
          placeholder="选择服务结束日期"
        />
      </el-form-item>
      <el-form-item
        label="配送时效约定"
        prop="remark"
      >
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入配送时效约定"
        />
      </el-form-item>
      <el-form-item
        label="摘要信息"
        prop="distributeAbstract"
      >
        <el-input
          v-model="formData.distributeAbstract"
          type="textarea"
          placeholder="请输入配送服务摘要信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          :loading="subLoading"
          @click="submit"
        >
          <span v-if="dialogType!=='changeInfo'">提交审核</span>
          <span v-else>保存更新</span>
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import area from '@/utils/area.js'
import { useRoute } from 'vue-router'

export default defineComponent({
  name: 'CreateService',
  emits: ['onsuccess'],
  setup(props, context) {
    const api = inject('api')
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const citys = area
    const formRef = ref(null)
    const cascader = ref(null)
    var reactiveData = reactive({
      dataLoading: false,
      subLoading: false,
      dialogTitle: '新建配送服务',
      dialogType: 'create',
      distributorDetail: null,
      productOptions: [],
      contractOptions: [],
      contractForm: {
        objectId: 0,
        contractObjectType: 'distribute',
        contractType: 'distribute_contrart',
        keyWord: '',
      },
      currentSelect: null,
      proLoading: false,
      formData: {
        distributeId: Number(route.query.id) || 0,
        contractId: undefined,
        productId: '',
        sellUnit: '',
        sellUnitLabel: '',
        region: [],
        expireTime: '',
        distributePrice: '',
        distributePercent: '',
        computeMode: '固定价格',
        remark: '',
        distributeAbstract: '',
      },
    })
    const distributePricePass = (rule, value, callback) => {
      if (Number(value) >= 0) {
        if (Number(value) > 0) {
          reactiveData.formData.distributePrice = Number(value)
          callback()
        } else {
          callback(new Error('配送费必须大于0'))
        }
      } else {
        callback(new Error('请输入配送费'))
      }
    }
    const distributePercentPass = (rule, value, callback) => {
      if (Number(value) >= 0) {
        if (Number(value) > 0 && Number(value) < 100) {
          reactiveData.formData.distributePercent = Number(value)
          callback()
        } else {
          callback(new Error('请输入0~100之间的数字'))
        }
      } else {
        callback(new Error('请输入配送费'))
      }
    }
    var formRules = reactive({
      productId: [
        { required: true, message: '请选择配送产品', trigger: 'change' },
      ],
      area: [
        {
          required: true,
          message: '请选择配送地区',
          trigger: 'change',
        },
      ],
      expireTime: [
        {
          required: true,
          message: '请选择服务结束日期',
          trigger: 'change',
        },
      ],
      distributePrice: [
        {
          required: true,
          validator: distributePricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      distributePercent: [
        {
          required: true,
          validator: distributePercentPass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      remark: [],
      distributeAbstract: [],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = async(type, detail) => {
      reactiveData.dialogType = type
      reactiveData.distributorDetail = detail.distributorDetail
      reactiveData.contractForm.objectId =
        detail.distributorDetail?.id || Number(route.query.id)
      reactiveData.formData.distributeId =
        detail.distributorDetail?.id || Number(route.query.id)
      reactiveData.formData.distributeName =
        detail.distributorDetail.distributeName
      // 弹框标题
      if (reactiveData.dialogType === 'create') {
        reactiveData.dialogTitle = '新建配送服务'
      } else if (reactiveData.dialogType === 'edit') {
        reactiveData.dialogTitle = '编辑配送服务'
      } else {
        reactiveData.dialogTitle = '变更配送服务'
      }
      if (
        reactiveData.dialogType === 'edit' ||
        reactiveData.dialogType === 'changeInfo'
      ) {
        getDistributeServerDetail(detail)
      }

      // 获取有效合同列表
      getValidContract()

      // 获取有效产品列表
      productList()

      dialogShow.value = true
    }
    // 获取配送服务详情
    const getDistributeServerDetail = async(detail) => {
      reactiveData.dataLoading = true
      var disService = await api.distributors.DISTRIBUTORS_SERVICE_DETAIL({
        id: detail.serviceData.id,
      })
      if (disService.code === 0) {
        var datas = {
          ...disService.data.DistributeServe,
          productId: disService.data.DistributeServe.productId,
          contractId: disService.data.DistributeServe.contractId || undefined,
          area: currentInstance.proxy.getCascaderAreaData(
            disService.data.DistributeServe.region
          ),
        }
        if (disService.data.DistributeServe.computeMode === '终端价百分比') {
          datas.distributePrice = ''
          datas.distributePercent =
            disService.data.DistributeServe.distributePrice
        } else if (disService.data.DistributeServe.computeMode === '固定价格') {
          datas.distributePercent = ''
        }
        reactiveData.formData = datas
        reactiveData.dataLoading = false
      }
    }
    const disabledDate = (date) => {
      // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
      return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
    }
    const radioChange = (val) => {
      console.log(val)
      formRef.value.validateField(['distributePrice', 'distributePercent'])
    }
    const getValidContract = () => {
      api.common.VALID_CONTRACT_LIST(reactiveData.contractForm).then((res) => {
        if (res.code === 0) {
          reactiveData.contractOptions = res.data.list || []
        }
      })
    }
    const productList = () => {
      api.common.GET_PRODUCT_LIST().then((res) => {
        if (res.code === 0) {
          reactiveData.productOptions = res.data.list
        }
      })
    }
    const proRemoteMethod = async(query) => {
      if (query !== '') {
        reactiveData.proLoading = true
        var pro = await api.common.GET_PRODUCT_LIST({ keyWord: query })
        if (pro.code === 0) {
          reactiveData.productOptions = pro.data.list
        } else {
          reactiveData.productOptions = []
        }
        reactiveData.proLoading = false
      } else {
        reactiveData.productOptions = []
      }
    }
    const close = () => {
      reactiveData.formData.distributePercent = ''
      reactiveData.formData.distributePrice = ''
      formRef.value.resetFields()
      setTimeout(() => {
        formRef.value.clearValidate()
        dialogShow.value = false
      }, 100)
    }
    const selectChange = (id) => {
      var item = reactiveData.productOptions.find((p) => p.id)
      if (item) {
        reactiveData.currentSelect = item
        reactiveData.formData.sellUnit = item.sellUnit
        reactiveData.formData.sellUnitLabel = currentInstance.proxy.getLabel(
          'sell_unit',
          item.sellUnit
        )
      }
    }
    const areaChange = (val) => {
      console.log(val)
      reactiveData.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
    }
    const subdataOperation = () => {
      if (reactiveData.formData.computeMode === '终端价百分比') {
        reactiveData.formData.distributePrice =
          reactiveData.formData.distributePercent
      }
    }
    const createOperation = () => {
      reactiveData.subLoading = true
      subdataOperation()
      api.distributors
        .DISTRIBUTORS_SERVICE_CREATE(reactiveData.formData)
        .then((res) => {
          if (res.code === 0) {
            context.emit('onsuccess')
            currentInstance.proxy.customMessage({
              type: 'success',
              message:
                '<新建配送服务审核>已提交，可在[流程审批-我发起的]查看审核进程。',
            })
            close()
            reactiveData.subLoading = false
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
            reactiveData.subLoading = false
          }
        })
    }
    const editOperation = () => {
      reactiveData.subLoading = true
      subdataOperation()
      api.distributors
        .DISTRIBUTORS_SERVICE_EIDT(reactiveData.formData)
        .then((res) => {
          if (res.code === 0) {
            context.emit('onsuccess')
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '编辑成功',
            })
            close()
            reactiveData.subLoading = false
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
            reactiveData.subLoading = false
          }
        })
    }
    const updateOperation = () => {
      reactiveData.subLoading = true
      subdataOperation()
      api.distributors
        .DISTRIBUTORS_SERVICE_UPDATE(reactiveData.formData)
        .then((res) => {
          if (res.code === 0) {
            context.emit('onsuccess')
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '信息变更成功',
            })
            close()
            reactiveData.subLoading = false
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
            reactiveData.subLoading = false
          }
        })
    }
    const submit = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (reactiveData.dialogType === 'create') {
            createOperation()
          } else if (reactiveData.dialogType === 'edit') {
            editOperation()
          } else if (reactiveData.dialogType === 'changeInfo') {
            updateOperation()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      citys,
      formRef,
      cascader,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      submit,
      selectChange,
      areaChange,
      proRemoteMethod,
      radioChange,
      disabledDate,
    }
  },
})
</script>
